#include "World.h"

#include <cstring>
using std::memset;

#include "grid/SimpleGrid.h"

/*
	World
*/

/*	public	*/

World::World(int width, int height) :
	_width(width),
	_height(height),
	_boundingBoxWidth(width),
	_boundingBoxHeight(height),
	_x1(width),
	_x2(0),
	_y1(height),
	_y2(0),
	_cellIdGenerator(0) {

	/* _grid */
	int gridLength = width * height;
	_grid = new CellId[gridLength];
	memset(_grid, 0, gridLength * sizeof(CellId));

	/* _idToCell */
	int idToCellLength = CELLID_MAX + 1;
	_idToCell = new Cell*[idToCellLength];
	memset(_idToCell, 0, idToCellLength * sizeof(Cell*));
}

World::~World() {
	/* _grid */
	delete[] _grid;

	/* _idToCell */
	deleteall<Cell>(_idToCell, CELLID_MAX + 1);
	delete[] _idToCell;
}

void World::addCell(Cell* cell) {
	_idToCell[cell->getId()] = cell;
}

int World::getWidth() const {
	return _width;
}

int World::getHeight() const {
	return _height;
}

Cell* World::getCell(CellId id) {
	return _idToCell[id];
}

Cell const* World::getCell(CellId id) const {
	return _idToCell[id];
}

CellId World::getNewCellId() const {
	World& self = const_cast<World&>(*this);
	++(self._cellIdGenerator);
	assert(_cellIdGenerator != 0);
	return _cellIdGenerator;
}

CellId World::getMaxCellId() const {
	return _cellIdGenerator;
}

SimpleGrid* World::getSimpleGridCopy() const {
	/* width/height */
	int width  = _width;
	int height = _height;

	/* result grid */
	SimpleGrid* simpleGrid = new SimpleGrid(width, height);

	for(int i = 0; i != width; ++i) {
		for(int j = 0; j != height; ++j) {
			simpleGrid->setTile(i, j, grid(i, j));
		}
	}

	return simpleGrid;
}

